package com.fuqi.android.zhongcai.base.view.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.HeaderViewListAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.fuqi.android.zhongcai.R;
import com.fuqi.android.zhongcai.application.UniApplication;
import com.fuqi.android.zhongcai.base.Constants;
import com.fuqi.android.zhongcai.base.mvp.presenter.AboutPresenterInter;
import com.fuqi.android.zhongcai.base.mvp.view.IAboutView;
import com.fuqi.android.zhongcai.base.request.api.LocationApi;
import com.fuqi.android.zhongcai.base.request.result.NullResult;
import com.fuqi.android.zhongcai.base.view.adapter.MainTabAdapter;
import com.fuqi.android.zhongcai.base.view.fragment.OrderParentFragment;
import com.fuqi.android.zhongcai.base.view.widget.CustomProgress;
import com.fuqi.android.zhongcai.base.view.widget.NoScrollViewPager;
import com.fuqi.android.zhongcai.base.view.widget.TitleBar;
import com.fuqi.android.zhongcai.business.shuig.request.api.CheckSaveApi;
import com.fuqi.android.zhongcai.business.shuig.view.adapter.DaiChouChaAdapter;
import com.fuqi.android.zhongcai.service.DicSyncService;
import com.fuqi.android.zhongcai.service.ImageUploadService;
import com.fuqi.android.zhongcai.sql.dao.SQLDao;
import com.fuqi.android.zhongcai.utils.ActivityUtils;
import com.fuqi.android.zhongcai.utils.LogUtils;
import com.fuqi.framework.gson.GsonHelper;
import com.fuqi.framework.network.code.HandleCode;
import com.fuqi.framework.network.http.RequestManager;
import com.fuqi.framework.utils.NetworkUtils;
import com.fuqi.framework.utils.StringUtil;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 *  Tab页
 */
public class MainTabActivity extends BaseActivity implements OnCheckedChangeListener , IAboutView ,EasyPermissions.PermissionCallbacks{

	@Bind(R.id.viewpager)
	NoScrollViewPager viewPager;
	@Bind(R.id.rg_group)
	RadioGroup radioGroup;
	@Bind(R.id.rb_order)
	RadioButton rbOrder;
	@Bind(R.id.rb_user_center)
	RadioButton rbUserCenter;
	AboutPresenterInter aboutPresenter;

	// 定位相关
	LocationClient mLocClient;
	private static final int  REQUEST_CODE_PERMISSION_LOCATION = 1;
	int iSpan = 20000; // 20s定位1次并上次位置信息
	double lat,lon;

	List<String> orderIds;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Intent intent = new Intent(MainTabActivity.this, DicSyncService.class);
		startService(intent);
		setLocation();

		if(NetworkUtils.isCanUploadImg(this)) {
			int count = SQLDao.getInstance(this).selectCacheCount();
			if (count > 0) {
				switch (UniApplication.getInstance().getCurrentRole()) { // 是工人才能提交
					case Constants.ROLE_SGGR:
						startService(new Intent(this, ImageUploadService.class));
						break;

				}
			}
		}

		/*aboutPresenter = new AboutPresenterImpl(this);
		viewPager.post(new Runnable() {
			@Override
			public void run() {
				aboutPresenter.checkNewVersion();
			}
		});*/
	}


	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// TODO Auto-generated method stub

		switch (checkedId) {

		case R.id.rb_home:
			switchFragment(Constants.TAB_HOME);
			break;
		case R.id.rb_order:
			switchFragment(Constants.TAB_ORDER);
			break;
		case R.id.rb_user_center:
			switchFragment(Constants.TAB_USER_CENTER);
			break;
		default:
			switchFragment(Constants.TAB_HOME);
			break;

		}

	}

	TitleBar.ImageAction ti = new TitleBar.ImageAction(R.mipmap.ic_call) {
		@Override
		public void performAction(View view) {

			ActivityUtils.startActivity(MainTabActivity.this,ContactUsActivity.class);

		}
	};
	TitleBar.TextAction tt = new TitleBar.TextAction("确定") {
		@Override
		public void performAction(View view) {
			try {
				orderIds = new ArrayList<>();
				Fragment f0 = mainTabAdapter.getItem(viewPager.getCurrentItem());
				Fragment f = ((OrderParentFragment) f0).mAdapter.getItem(0);
	//			Fragment f = f0.getChildFragmentManager().findFragmentByTag("待抽查");
				PullToRefreshListView mRecyclerView = (PullToRefreshListView) f.getView().findViewById(R.id.recyclerview);
				SparseBooleanArray poss = mRecyclerView.getRefreshableView().getCheckedItemPositions();
				for (int i = 0; i < poss.size(); i++) {
					int key = poss.keyAt(i);
					if (poss.get(key)) {
						orderIds.add(((DaiChouChaAdapter) ((HeaderViewListAdapter) mRecyclerView.getRefreshableView().getAdapter()).getWrappedAdapter()).getDate().get(key - 1).getOrderId());
					}
				}
				if(orderIds.size() != 3){
					ActivityUtils.toast("请选择3条记录。");
					return;
				}else{
					CustomProgress.show(MainTabActivity.this, "正在处理...",true,null);
					RequestManager.getInstance().call(new CheckSaveApi(new CheckSaveApi.CheckSaveParams(StringUtil.getListString(orderIds)),
							respOrderListener, errorListener));
//					ActivityUtils.toast("Succ。" + StringUtil.getListString(orderIds));
				}
			}catch(Exception e){

			}
		}
	};
	Response.Listener<NullResult> respOrderListener = new Response.Listener<NullResult>() {

		@Override
		public void onResponse(NullResult response) {
			CustomProgress.close();
			if (HandleCode.requestSuccess()) {
				try {
					Fragment f0 = mainTabAdapter.getItem(viewPager.getCurrentItem());
					Fragment f = ((OrderParentFragment) f0).mAdapter.getItem(0);
					f.onResume();
				}catch(Exception e){

				}
			}
		}
	};

	public void switchFragment(int position) {

		switch (position) {
		case Constants.TAB_HOME:
			titleBar.setTitle("中财管道");
			titleBar.getmRightLayout().setVisibility(View.VISIBLE);
			viewPager.setCurrentItem(Constants.TAB_HOME, false);
			titleBar.addAction(ti);
			titleBar.removeAction(tt);
			break;
		case Constants.TAB_ORDER:
			if (UniApplication.getInstance().getCurrentRole().equals(Constants.ROLE_JCY)){
				titleBar.setTitle("抽查汇总");
				titleBar.getmRightLayout().setVisibility(View.VISIBLE);

				titleBar.addAction(tt);

			} else {
				titleBar.removeAction(tt);
				titleBar.setTitle("我的订单");
				titleBar.getmRightLayout().setVisibility(View.GONE);
			}

			titleBar.removeAction(ti);
			viewPager.setCurrentItem(Constants.TAB_ORDER, false);
			break;
		case Constants.TAB_USER_CENTER:
			if (UniApplication.getInstance().hasLogin()){

				if (UniApplication.getInstance().getUserInfo().getName() == null || UniApplication.getInstance().getUserInfo().getName().equals("")) {

					titleBar.setTitle("未设置昵称");

				} else {

					titleBar.setTitle(UniApplication.getInstance().getUserInfo().getName());
				}

			} else {
				titleBar.setTitle("未登录");
			}
			titleBar.removeAction(ti);
			titleBar.removeAction(tt);
			titleBar.getmRightLayout().setVisibility(View.GONE);
			viewPager.setCurrentItem(Constants.TAB_USER_CENTER, false);
			break;
		default:
			titleBar.removeAction(ti);
			titleBar.removeAction(tt);
			titleBar.setTitle("中财管道");
			titleBar.getmRightLayout().setVisibility(View.VISIBLE);
			viewPager.setCurrentItem(Constants.TAB_HOME, false);
			break;
		}
	}



	@Override
	protected void onResume() {
		super.onResume();
		// pager.startAutoScroll();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// pager.stopAutoScroll();
	}

	@Override
	protected void onDestroy() {
		if(mLocClient !=null)
			mLocClient.stop();
		super.onDestroy();

	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			exitBy2Click(); // 调用双击退出函数
			return false;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	}

	/**
	 * 双击退出函数
	 */
	private static Boolean isExit = false;

	@SuppressWarnings("deprecation")
	private void exitBy2Click() {
		Timer tExit = null;
		if (isExit == false) {
			isExit = true; // 准备退出
			ActivityUtils.toast("再按一次退出程序");
			tExit = new Timer();
			tExit.schedule(new TimerTask() {
				@Override
				public void run() {
					isExit = false; // 取消退出
				}
			}, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

		} else {
			finish();
			System.exit(0);
		}
	}
	MainTabAdapter mainTabAdapter;
	@Override
	public void initView() {

		titleBar.setTitle("中财");
		titleBar.getmLeftText().setVisibility(View.GONE);
		titleBar.addAction(ti);
		mainTabAdapter = new MainTabAdapter(getSupportFragmentManager());
		viewPager.setAdapter(mainTabAdapter);
		viewPager.setOffscreenPageLimit(0);



		if (UniApplication.getInstance().getCurrentRole().equals(Constants.ROLE_GRKH)){
			// 用户


		} else if (UniApplication.getInstance().getCurrentRole().equals(Constants.ROLE_SGGR)){
            // 施工工人

		}else if (UniApplication.getInstance().getCurrentRole().equals(Constants.ROLE_JCY)){
            // 监察员
			rbOrder.setText("抽查汇总");

		}else if (UniApplication.getInstance().getCurrentRole().equals(Constants.ROLE_NQ)){
			// 内勤



		}else if (UniApplication.getInstance().getCurrentRole().equals(Constants.ROLE_SGDZ)){
			// 施工队长
		}


	}

	@Override
	public void initListener() {

		radioGroup.setOnCheckedChangeListener(this);

	}

	@Override
	public void initData() {


	}

	@Override
	public boolean hasTitleBar() {
		return true;
	}


	@Override
	public int getLayoutId() {
		return R.layout.activity_main_tab;
	}




	@AfterPermissionGranted(REQUEST_CODE_PERMISSION_LOCATION)
	private void setLocation() {
		String[] perms = {Manifest.permission.READ_PHONE_STATE ,Manifest.permission.ACCESS_COARSE_LOCATION ,Manifest.permission.ACCESS_FINE_LOCATION };
		if (EasyPermissions.hasPermissions(this, perms)) {
			LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
			if(!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
			{
				// 未打开位置开关，可能导致定位失败或定位不准，提示用户或做相应处理
			}
			// 定位初始化
			mLocClient = new LocationClient(this);
			mLocClient.registerLocationListener(new MyDBLocationListener());
			LocationClientOption option = new LocationClientOption();
			option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
			);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
//			option.setOpenGps(true);// 打开gps
			option.setCoorType("GCJ-02"); // 设置坐标类型
			option.setScanSpan(iSpan);
			option.setLocationNotify(true);
			mLocClient.setLocOption(option);
			mLocClient.start();
		} else {
			EasyPermissions.requestPermissions(this, "定位需要以下权限:\n\n1.获取本机定位信息", REQUEST_CODE_PERMISSION_LOCATION, perms);
		}
	}


	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
	}

	@Override
	public void onPermissionsGranted(int requestCode, List<String> perms) {

	}

	@Override
	public void onPermissionsDenied(int requestCode, List<String> perms) {
		if (requestCode == REQUEST_CODE_PERMISSION_LOCATION) {
			Toast.makeText(this, "您拒绝了「定位」所需要的相关权限!", Toast.LENGTH_SHORT).show();
		}
	}



	class MyDBLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation arg0) {
			Log.e("ccqx","Latitude,Longitude" + arg0.getLatitude() + "," + arg0.getLongitude());
			Log.e("ccqx","getLocType" + arg0.getLocType());
			if(checkLocation(arg0)) {
				double tempLat = arg0.getLatitude();
				double tempLon = arg0.getLongitude();
				if(tempLat == lat && tempLon == lon){
					// 重复定位不提交
					return ;
				}
				lat = arg0.getLatitude();
				lon = arg0.getLongitude();
				RequestManager.getInstance().call(new LocationApi(new LocationApi.LocationParams(
						lat + "", lon + ""),
						respListener, errorListener));
			}
		}
	}

	boolean checkLocation(BDLocation arg0){
		if (arg0 == null)
			return false;
		switch (arg0.getLocType()){
			case BDLocation.TypeGpsLocation:
			case BDLocation.TypeNetWorkLocation:
			case BDLocation.TypeOffLineLocation:
				return true;
			case BDLocation.TypeCriteriaException:
			case BDLocation.TypeNetWorkException:
				return false;

		}
		return false;
	}


	Response.Listener<NullResult> respListener = new Response.Listener<NullResult>() {

		@Override
		public void onResponse(NullResult response) {
			if (HandleCode.requestSuccess()) {

			}
			LogUtils.i("response OrderListResult: " + GsonHelper.writeValue(response));
		}
	};


	Response.ErrorListener errorListener = new Response.ErrorListener() {

		@Override
		public void onErrorResponse(VolleyError error) {
			Log.i("juner", "juner  error.getMessage(): " + error.getMessage());

		}
	};


	@Override
	public void hasNewVersion() {
		ActivityUtils.toast("开始下载最新版本...");
		aboutPresenter.startUpdateVersion();
	}

	@Override
	public void noNewVersion() {
		ActivityUtils.toast("当前已是最新版本");
	}

	@Override
	public void checkNewVersionFailed() {
		//ActivityUtils.toast("check new version failed");
	}

}
